package demo12;

public class Test {

    public int search(int[] nums, int target) {
        int left = 0, right = nums.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] < target) left = mid + 1;
            else if (nums[mid] > target) right = mid - 1;
            else return mid;
        }
        return -1;
    }

    public int[] searchRange(int[] nums, int target) {
        int[] ret = new int[2];
        ret[0] = ret[1] = -1;
        //处理边界情况
        if (nums.length == 0) return ret;

        //二分左端点
        int left = 0, right = nums.length - 1;
        while (left < right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] < target) left = mid + 1;
            else right = mid;
        }
        //判断是否有结果
        if (nums[left] != target) return ret;
        else ret[0] = left;

        //二分右端点
        left = 0; right = nums.length - 1;
        while (left < right) {
            int mid = left + (right - left + 1) / 2;
            if (nums[mid] <= target) left = mid;
            else right = mid - 1;
        }
        ret[1] = left;
        return ret;
    }


    public void duplicateZeros(int[] arr) {
        //要记住证难则反
        //从前向后复写不行，就从后向前复写。
        int dest = -1, cur = 0, n = arr.length;
        //1.找到复写的位置
        while (cur < n) {
            if (arr[cur] != 0) dest++;
            else dest += 2;
            if (dest >= n - 1) break;
            cur++;
        }
        //2.处理边界情况
        if (dest == n) {
            arr[n - 1] = 0;
            dest -= 2;
            cur--;
        }
        //3.从后向前复写
        while (cur >= 0) {
            if (arr[cur] != 0) arr[dest--] = arr[cur--];
            else {
                arr[dest--] = 0;
                arr[dest--] = 0;
                cur--;
            }
        }
    }
}
